package SocialNet;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.NoSuchElementException;

import org.neo4j.helpers.collection.PositionedIterator;

class StatusIterator implements Iterator<Status> {
    private ArrayList<PositionedIterator<Status>> statuses = new ArrayList<PositionedIterator<Status>>();
    private StatusComparator comparator = new StatusComparator();

    public StatusIterator( Person person )
    {
        for ( Person friend : person.getFriends() )
        {
            Iterator<Status> iterator = friend.getStatus().iterator();
            if (iterator.hasNext()) {
                statuses.add(new PositionedIterator<Status>(iterator));
            }
        }
        sort();
    }

    public boolean hasNext()
    {
        return statuses.size() > 0;
    }

    public Status next()
    {
        if ( statuses.size() == 0 )
        {
            throw new NoSuchElementException();
        }
        // START SNIPPET: getActivityStream
        PositionedIterator<Status> first = statuses.get(0);
        Status returnVal = first.current();

        if ( !first.hasNext() )
        {
            statuses.remove( 0 );
        }
        else
        {
            first.next();
            sort();
        }

        return returnVal;
        // END SNIPPET: getActivityStream
    }

    private void sort()
    {
        Collections.sort( statuses, comparator );
    }

    public void remove()
    {
        throw new UnsupportedOperationException( "Don't know how to do that..." );
    }

    private class StatusComparator implements Comparator<PositionedIterator<Status>> {
        public int compare(PositionedIterator<Status> a, PositionedIterator<Status> b) {
            return a.current().getDate().compareTo(b.current().getDate());
        }
    }
}
